<template>
  <div class="goods-view">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">商品中心</h1>
        <p class="page-subtitle">发现更多优质商品</p>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <div class="container">
        <el-row :gutter="24">
          <!-- 侧边栏筛选 -->
          <el-col
            :span="6"
            :xs="24"
            :sm="24"
            :md="6"
            class="sidebar-col"
          >
            <div class="filter-sidebar">
              <div class="filter-header">
                <h3>商品筛选</h3>
                <el-button
                  text
                  type="primary"
                  @click="resetFilters"
                >重置</el-button>
              </div>

              <!-- 商品分类 -->
              <div class="filter-section">
                <h4 class="filter-title">商品分类</h4>
                <el-radio-group
                  v-model="selectedCategory"
                  @change="handleCategoryChange"
                >
                  <el-radio
                    label=""
                    class="radio-item"
                  >全部</el-radio>
                  <el-radio
                    v-for="category in goodsStore.goodsTypes"
                    :key="category"
                    :label="category"
                    class="radio-item"
                  >
                    {{ category }}
                  </el-radio>
                </el-radio-group>
              </div>

              <!-- 价格区间 -->
              <div class="filter-section">
                <h4 class="filter-title">价格区间</h4>
                <el-radio-group
                  v-model="selectedPriceRange"
                  @change="handlePriceChange"
                >
                  <el-radio
                    v-for="range in priceRanges"
                    :key="range.label"
                    :label="range"
                    class="radio-item"
                  >
                    {{ range.label }}
                  </el-radio>
                </el-radio-group>
              </div>

              <!-- 商品状态 -->
              <div class="filter-section">
                <h4 class="filter-title">商品状态</h4>
                <el-checkbox
                  v-model="showOnlyAvailable"
                  @change="handleStatusChange"
                  class="checkbox-item"
                >
                  仅显示有货商品
                </el-checkbox>
              </div>
            </div>
          </el-col>

          <!-- 主内容区域 -->
          <el-col
            :span="18"
            :xs="24"
            :sm="24"
            :md="18"
            class="content-col"
          >
            <!-- 工具栏 -->
            <div class="toolbar">
              <el-row
                :gutter="16"
                justify="space-between"
                align="middle"
              >
                <el-col
                  :span="12"
                  :xs="24"
                  :sm="12"
                >
                  <el-input
                    v-model="searchKeyword"
                    placeholder="搜索商品名称或描述..."
                    class="search-input"
                    @keyup.enter="handleSearch"
                    clearable
                  >
                    <template #prefix>
                      <el-icon>
                        <Search />
                      </el-icon>
                    </template>
                  </el-input>
                </el-col>

                <el-col
                  :span="12"
                  :xs="24"
                  :sm="12"
                  class="toolbar-right"
                >
                  <div class="toolbar-actions">
                    <!-- 排序选择 -->
                    <el-select
                      v-model="sortBy"
                      placeholder="排序方式"
                      class="sort-select"
                      @change="handleSort"
                    >
                      <el-option
                        label="默认排序"
                        value="default"
                      />
                      <el-option
                        label="价格从低到高"
                        value="price-asc"
                      />
                      <el-option
                        label="价格从高到低"
                        value="price-desc"
                      />
                      <el-option
                        label="最新上架"
                        value="time-desc"
                      />
                    </el-select>

                    <!-- 视图切换 -->
                    <div class="view-toggle">
                      <el-button-group>
                        <el-button
                          :type="viewMode === 'grid' ? 'primary' : 'default'"
                          @click="viewMode = 'grid'"
                          size="small"
                        >
                          <el-icon>
                            <Grid />
                          </el-icon>
                        </el-button>
                        <el-button
                          :type="viewMode === 'list' ? 'primary' : 'default'"
                          @click="viewMode = 'list'"
                          size="small"
                        >
                          <el-icon>
                            <List />
                          </el-icon>
                        </el-button>
                      </el-button-group>
                    </div>
                  </div>
                </el-col>
              </el-row>

              <!-- 结果统计 -->
              <div class="result-info">
                <span>共找到 {{ goodsStore.total }} 件商品</span>
                <el-tag
                  v-if="selectedCategory"
                  type="info"
                  closable
                  @close="selectedCategory = ''"
                >
                  分类: {{ selectedCategory }}
                </el-tag>
                <el-tag
                  v-if="selectedPriceRange"
                  type="info"
                  closable
                  @close="selectedPriceRange = null"
                >
                  价格: {{ selectedPriceRange?.label }}
                </el-tag>
              </div>
            </div>

            <!-- 商品列表 -->
            <div
              v-loading="goodsStore.loading"
              class="goods-list"
            >
              <!-- 网格视图 -->
              <el-row
                v-if="viewMode === 'grid'"
                :gutter="24"
                class="goods-grid"
              >
                <el-col
                  v-for="product in displayedProducts"
                  :key="product.id"
                  :xs="12"
                  :sm="12"
                  :md="8"
                  :lg="6"
                  class="goods-col"
                >
                  <div
                    class="goods-card"
                    @click="goToProductDetail(product.id)"
                  >
                    <div class="goods-image">
                      <img
                        :src="product.goodsPic || defaultImage"
                        :alt="product.goodsName"
                        @error="handleImageError"
                      />
                      <div class="goods-overlay">
                        <el-button
                          type="primary"
                          size="small"
                          circle
                        >
                          <el-icon>
                            <View />
                          </el-icon>
                        </el-button>
                      </div>
                    </div>
                    <div class="goods-info">
                      <h3 class="goods-name">{{ product.goodsName }}</h3>
                      <p class="goods-desc">{{ product.goodsContent }}</p>
                      <div class="goods-footer">
                        <span class="goods-price">¥{{ product.goodsMoney }}</span>
                        <el-tag
                          :type="getGoodsTypeTag(product.goodsType)"
                          size="small"
                        >
                          {{ product.goodsType }}
                        </el-tag>
                      </div>
                    </div>
                  </div>
                </el-col>
              </el-row>

              <!-- 列表视图 -->
              <div
                v-if="viewMode === 'list'"
                class="goods-list-view"
              >
                <div
                  v-for="product in displayedProducts"
                  :key="product.id"
                  class="goods-list-item"
                  @click="goToProductDetail(product.id)"
                >
                  <div class="list-item-image">
                    <img
                      :src="product.goodsPic || defaultImage"
                      :alt="product.goodsName"
                      @error="handleImageError"
                    />
                  </div>
                  <div class="list-item-content">
                    <div class="list-item-header">
                      <h3 class="list-item-title">{{ product.goodsName }}</h3>
                      <el-tag
                        :type="getGoodsTypeTag(product.goodsType)"
                        size="small"
                      >
                        {{ product.goodsType }}
                      </el-tag>
                    </div>
                    <p class="list-item-desc">{{ product.goodsContent }}</p>
                    <div class="list-item-footer">
                      <span class="list-item-price">¥{{ product.goodsMoney }}</span>
                      <div class="list-item-time">{{ formatDate(product.createTime) }}</div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- 空状态 -->
              <div
                v-if="!goodsStore.loading && displayedProducts.length === 0"
                class="empty-state"
              >
                <el-empty description="暂无商品数据">
                  <el-button
                    type="primary"
                    @click="resetFilters"
                  >重置筛选条件</el-button>
                </el-empty>
              </div>
            </div>

            <!-- 分页 -->
            <div
              v-if="displayedProducts.length > 0"
              class="pagination-wrapper"
            >
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[12, 24, 48, 96]"
                :total="goodsStore.total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useGoodsStore } from '@/stores/goods'
import { Search, Grid, List, View } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const goodsStore = useGoodsStore()

// 响应式数据
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedPriceRange = ref<any>(null)
const showOnlyAvailable = ref(false)
const sortBy = ref('default')
const viewMode = ref('grid')
const currentPage = ref(1)
const pageSize = ref(12)

// 价格区间选项
const priceRanges = [
  { label: '全部价格', min: 0, max: Infinity },
  { label: '0-50元', min: 0, max: 50 },
  { label: '50-100元', min: 50, max: 100 },
  { label: '100-200元', min: 100, max: 200 },
  { label: '200-500元', min: 200, max: 500 },
  { label: '500元以上', min: 500, max: Infinity }
]

// 默认图片
const defaultImage =
  'https://images.unsplash.com/photo-1441986300917-64674bd600d8?w=300&h=300&fit=crop'

// 计算属性
const filteredProducts = computed(() => {
  let products = [...goodsStore.goodsList]

  // 按分类筛选
  if (selectedCategory.value) {
    products = products.filter((p) => p.goodsType === selectedCategory.value)
  }

  // 按价格筛选
  if (
    selectedPriceRange.value &&
    selectedPriceRange.value.label !== '全部价格'
  ) {
    products = products.filter(
      (p) =>
        p.goodsMoney >= selectedPriceRange.value.min &&
        p.goodsMoney <= selectedPriceRange.value.max
    )
  }

  // 按状态筛选
  if (showOnlyAvailable.value) {
    products = products.filter((p) => p.status === 0)
  }

  // 按关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    products = products.filter(
      (p) =>
        p.goodsName.toLowerCase().includes(keyword) ||
        p.goodsContent.toLowerCase().includes(keyword)
    )
  }

  // 排序
  switch (sortBy.value) {
    case 'price-asc':
      products.sort((a, b) => a.goodsMoney - b.goodsMoney)
      break
    case 'price-desc':
      products.sort((a, b) => b.goodsMoney - a.goodsMoney)
      break
    case 'time-desc':
      products.sort(
        (a, b) =>
          new Date(b.createTime).getTime() - new Date(a.createTime).getTime()
      )
      break
  }

  return products
})

const displayedProducts = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredProducts.value.slice(start, end)
})

// 方法
const handleCategoryChange = () => {
  currentPage.value = 1
  updateFilters()
}

const handlePriceChange = () => {
  currentPage.value = 1
  updateFilters()
}

const handleStatusChange = () => {
  currentPage.value = 1
  updateFilters()
}

const handleSearch = () => {
  currentPage.value = 1
  updateFilters()
}

const handleSort = () => {
  currentPage.value = 1
}

const resetFilters = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  selectedPriceRange.value = priceRanges[0]
  showOnlyAvailable.value = false
  sortBy.value = 'default'
  currentPage.value = 1
  updateFilters()
}

const updateFilters = () => {
  // 这里可以添加URL参数更新逻辑
  goodsStore.setSearchParams({
    goodsType: selectedCategory.value || undefined,
    goodsContent: searchKeyword.value || undefined,
    status: showOnlyAvailable.value ? 0 : undefined
  })
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
}

const goToProductDetail = (id: number) => {
  router.push(`/goods/${id}`)
}

const getGoodsTypeTag = (type: string) => {
  const tagMap: Record<string, string> = {
    女装: 'danger',
    男装: 'primary',
    童装: 'success',
    配饰: 'warning'
  }
  return tagMap[type] || 'info'
}

const handleImageError = (event: Event) => {
  const target = event.target as HTMLImageElement
  target.src = defaultImage
}

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 监听路由查询参数
watch(
  () => route.query,
  (newQuery) => {
    if (newQuery.goodsType) {
      selectedCategory.value = newQuery.goodsType as string
    }
    if (newQuery.search) {
      searchKeyword.value = newQuery.search as string
    }
  },
  { immediate: true }
)

// 生命周期
onMounted(() => {
  goodsStore.fetchGoodsList()
  selectedPriceRange.value = priceRanges[0]
})
</script>

<style scoped>
.goods-view {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 页面头部 */
.page-header {
  background: white;
  border-bottom: 1px solid #ebeef5;
  padding: 32px 0;
}

.page-title {
  font-size: 32px;
  font-weight: 700;
  color: #303133;
  margin-bottom: 8px;
}

.page-subtitle {
  color: #606266;
  font-size: 16px;
}

/* 主要内容 */
.main-content {
  padding: 32px 0;
}

.sidebar-col {
  margin-bottom: 24px;
}

.content-col {
  margin-bottom: 24px;
}

/* 筛选侧边栏 */
.filter-sidebar {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 100px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.filter-header h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.filter-section {
  margin-bottom: 24px;
}

.filter-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.radio-item,
.checkbox-item {
  display: block !important;
  margin-bottom: 8px;
  margin-right: 0 !important;
}

/* 工具栏 */
.toolbar {
  background: white;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.toolbar-right {
  display: flex;
  justify-content: flex-end;
}

.toolbar-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.sort-select {
  width: 140px;
}

.result-info {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #ebeef5;
  display: flex;
  align-items: center;
  gap: 12px;
  color: #606266;
  font-size: 14px;
}

/* 商品列表 */
.goods-list {
  min-height: 400px;
}

.goods-grid {
  margin-bottom: 32px;
}

.goods-col {
  margin-bottom: 24px;
}

.goods-card {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.goods-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.goods-image {
  position: relative;
  width: 100%;
  height: 200px;
  overflow: hidden;
}

.goods-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.goods-card:hover .goods-image img {
  transform: scale(1.05);
}

.goods-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.goods-card:hover .goods-overlay {
  opacity: 1;
}

.goods-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.goods-name {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.goods-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.goods-price {
  font-size: 18px;
  font-weight: 700;
  color: #e74c3c;
}

/* 列表视图 */
.goods-list-view {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.goods-list-item {
  display: flex;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.goods-list-item:hover {
  background-color: #f5f7fa;
}

.goods-list-item:last-child {
  border-bottom: none;
}

.list-item-image {
  width: 120px;
  height: 120px;
  margin-right: 20px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.list-item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.list-item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.list-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.list-item-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.list-item-desc {
  color: #606266;
  font-size: 14px;
  line-height: 1.6;
  margin-bottom: 16px;
  flex: 1;
}

.list-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.list-item-price {
  font-size: 20px;
  font-weight: 700;
  color: #e74c3c;
}

.list-item-time {
  color: #909399;
  font-size: 14px;
}

/* 分页 */
.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 32px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .main-content {
    padding: 16px 0;
  }

  .filter-sidebar {
    position: static;
  }

  .toolbar {
    padding: 16px;
  }

  .toolbar-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .sort-select {
    width: 100%;
  }

  .result-info {
    flex-wrap: wrap;
  }

  .goods-image {
    height: 160px;
  }

  .goods-list-item {
    flex-direction: column;
  }

  .list-item-image {
    width: 100%;
    height: 200px;
    margin-right: 0;
    margin-bottom: 16px;
  }
}
</style> 